import { message } from 'antd';
import { useEffect } from 'react';
import { matchRoutes, useLocation, useNavigate } from 'react-router-dom';
import routes from './routes';
import { USER_KEY } from '@/constants';
import MyLocalStorage from '@/utils/Mylocalstorage';

const AuthRoute = ({ children }: any) => {
  const navigate = useNavigate();
  const { state, pathname, search } = useLocation();
  const token = MyLocalStorage.localstorage.getItem<UserInfo>(USER_KEY)?.token;
  const permissionList = MyLocalStorage.localstorage.getItem<UserInfo>(USER_KEY)?.permission?.concat(['/']);
  const is403 = permissionList?.every((path) => !pathname.includes(path));
  useEffect(() => {
    if (!token) {
      message.error('未登录,请先登录!');
      navigate('/login');
      return;
    }
    // if (!isExist) return navigate('/404');
    if (is403) return navigate('/403');
    if (pathname == '/' /* || pathname == '/login' */) {
      navigate(permissionList[0] + search);
    } else {
      // 如果是其他路由就跳到其他的路由
      navigate(pathname + search, { state });
    }
  }, [token, pathname]);

  return children;
};

export default AuthRoute;
